package com.hsogoo.game.server;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.hsogoo.game.event.JoinRoomEvent;
import com.hsogoo.game.msg.JoinRoomMessage;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by za-huangsaigang on 2017/12/6.
 */
@Slf4j
public class GameEventDispatcher implements ApplicationContextAware{

    private ApplicationContext applicationContext;
    private SocketIOServer server;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void setServer(SocketIOServer server) {
        this.server = server;
    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        log.info("client disconnected");
    }

    @OnConnect
    public void onConnect(SocketIOClient client) {
        log.info(this + "client connected");
    }

    @OnEvent(value = "joinRoom")
    public void joinRoom(SocketIOClient client , String data){

        log.info(this + "client join room");
        JoinRoomMessage message = JSON.parseObject(data , JoinRoomMessage.class) ;
        JoinRoomEvent event = new JoinRoomEvent(this);
        event.setClient(client);
        event.setName(message.getName());
        applicationContext.publishEvent(message);
        log.info("event is published");
    }

}
